{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 张量计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tvm\n",
    "from tvm import te"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = te.size_var(\"n\")\n",
    "m = te.size_var(\"m\")\n",
    "A = te.placeholder((n, m), name=\"A\")\n",
    "k = te.reduce_axis((0, m), \"k\")\n",
    "k_ = te.reduce_axis((0, m - 1), \"k_\")\n",
    "f1 = lambda i: te.sum(A[i, k], axis=k)\n",
    "f2 = lambda i: A[i, 0] + 1\n",
    "f3 = lambda i: te.sum(A[i, k], axis=k) + 1\n",
    "f4 = lambda i: A[i, 0] * (te.sum(A[i, k], axis=k) + 1)\n",
    "f5 = lambda i: (te.sum(A[i, k], axis=k), A[i, 0] + 1)\n",
    "f6 = lambda i: (te.sum(A[i, k], axis=k), te.sum(A[i, k_], axis=k_))\n",
    "\n",
    "#\n",
    "# Valid compute\n",
    "try:\n",
    "    B = te.compute((n,), f1, name=\"B\")\n",
    "except tvm._ffi.base.TVMError as ex:\n",
    "    assert False\n",
    "\n",
    "#\n",
    "# Valid compute\n",
    "try:\n",
    "    B = te.compute((n,), f2, name=\"B\")\n",
    "except tvm._ffi.base.TVMError as ex:\n",
    "    assert False\n",
    "\n",
    "#\n",
    "# Invalid compute with non top level reduction\n",
    "try:\n",
    "    B = te.compute((n,), f3, name=\"B\")\n",
    "    assert False\n",
    "except tvm._ffi.base.TVMError as ex:\n",
    "    pass\n",
    "\n",
    "#\n",
    "# Invalid compute with non top level reduction\n",
    "try:\n",
    "    B = te.compute((n,), f4, name=\"B\")\n",
    "    assert False\n",
    "except tvm._ffi.base.TVMError as ex:\n",
    "    pass\n",
    "\n",
    "#\n",
    "# Invalid compute with reduction and non-reduction batch ops\n",
    "try:\n",
    "    B0, B1 = te.compute((n,), f5, name=\"B\")\n",
    "    assert False\n",
    "except tvm._ffi.base.TVMError as ex:\n",
    "    pass\n",
    "\n",
    "#\n",
    "# Invalid compute with unequal batch reduction ops\n",
    "try:\n",
    "    B0, B1 = te.compute((n,), f6, name=\"B\")\n",
    "    assert False\n",
    "except tvm._ffi.base.TVMError as ex:\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ai",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
